package com.example.order;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.order.fragment.ConsumerOrderFoodFragment;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Random;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    private static final String TAG = "LOG";
    private Context context;

    // Add these fields for the backend connection
    private static final String LOGIN_URL = "http://10.2.0.232:8080/app/authenticate";
    private String username;
    private String password;

    private String requestBody;

    private String generatedCaptcha;


    // btnLogin点击事件
    public void btnLoginClick(View v) {
        Log.e(TAG, "onClick");
        EditText etUser = findViewById(R.id.editName);
        String strUser = etUser.getText().toString().trim();
        EditText edtPass = findViewById(R.id.editPass);
        String strPass = edtPass.getText().toString().trim();
        EditText editCaptcha = findViewById(R.id.editCaptcha);
        String enteredCaptcha = editCaptcha.getText().toString().trim();

        // Check if username is empty
        if (strUser.equals("")) {
            Toast.makeText(LoginActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // Check if password is empty
        if (strPass.equals("")) {
            Toast.makeText(LoginActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // Check if entered captcha is empty
        if (enteredCaptcha.equals("")) {
            Toast.makeText(LoginActivity.this, "验证码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // Set username and password for backend connection
        username = strUser;
        password = strPass;


        // 构建 JSON 请求体
        JSONObject jsonRequest = new JSONObject();
        try {
            jsonRequest.put("username", username);
            jsonRequest.put("password", password);
            requestBody = jsonRequest.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // If you want to keep using the existing checks, you can add your new LoginAsyncTask here
        // 执行登录操作
        new LoginAsyncTask().execute();
    }

    // Add this AsyncTask for backend connection
    private class LoginAsyncTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... voids) {

            // 验证验证码
            if (!validateCaptcha()) {
                return "Error: 验证码错误";
            }

            // 其他代码保持不变
            try {
                // 使用 OkHttp 进行登录请求
                OkHttpClient client = new OkHttpClient();
                MediaType JSON = MediaType.parse("application/json; charset=utf-8");

                System.out.println(requestBody);
                // 将 JSON 请求体添加到请求中
                RequestBody body = RequestBody.create(JSON, requestBody);

                // 构建 HTTP 请求
                Request request = new Request.Builder()
                        .url(LOGIN_URL)
                        .post(body)
                        .build();

                Response response = client.newCall(request).execute();
                return response.body().string();

            } catch (IOException e) {
                e.printStackTrace();
                return "Error: " + e.getMessage();
            }
        }

        // 新增方法用于验证验证码
        private boolean validateCaptcha() {
            EditText editCaptcha = findViewById(R.id.editCaptcha);
            String enteredCaptcha = editCaptcha.getText().toString().trim();
            ImageView imageViewCaptcha = findViewById(R.id.imageViewCaptcha);
            String currentCaptcha = getCaptchaFromImage(imageViewCaptcha);

            return enteredCaptcha.equals(currentCaptcha);
        }

        // 新增方法用于从验证码图片获取验证码
        private String getCaptchaFromImage(ImageView imageViewCaptcha) {

            return generatedCaptcha;
        }



        protected void onPostExecute(String result) {
            Log.d("LoginAsyncTask", "Raw Result: " + result);

            if (result != null && result.startsWith("Error")) {
                // 处理错误逻辑
                Log.e("LoginAsyncTask", "Login error: " + result);

                if (result.contains("验证码错误")) {
                    // 验证码错误的提示
                    Toast.makeText(context, "验证码错误", Toast.LENGTH_SHORT).show();
                } else if (result.contains("用户名或密码错误")) {
                    // 用户名或密码错误的提示
                    Toast.makeText(context, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                } else if (result.contains("failure")) {
                    // 登录失败的提示
                    Toast.makeText(context, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                } else {
                    // 其他错误的提示
                    if (context != null) {
                        Toast.makeText(context, "登录失败：" + result, Toast.LENGTH_SHORT).show();
                    }
                }
            } else {
                // 处理成功的逻辑
                try {
                    // 直接构建 JSONObject
                    JSONObject jsonResult = new JSONObject(result);

                    // 输出日志以确认用户类型信息
                    Log.d("LoginAsyncTask", "JSON Result: " + jsonResult.toString());

                    // 处理 JSON 数据
                    String resultStatus = jsonResult.optString("result");

                    System.out.println(jsonResult);
                    if ("success".equals(resultStatus)) {
                        // 登录成功
                        Toast.makeText(context, jsonResult.optString("message"), Toast.LENGTH_SHORT).show();

                        // 在Intent中保存用户名
                        Intent intent;

                        if ("user".equals(jsonResult.getString("userType"))) {
                            // 用户类型是user
                            Log.d("LoginAsyncTask", "User type: user");

                            intent = new Intent(context, ConsumerActivity.class);
                            intent.putExtra("consumer_id", username);

                            // 将用户名保存为Fragment的参数
                            ConsumerOrderFoodFragment fragment = new ConsumerOrderFoodFragment();
                            Bundle args = new Bundle();
                            args.putString("consumer_id", username);
                            fragment.setArguments(args);

                            if (intent.resolveActivity(getPackageManager()) != null) {
                                startActivity(intent);
                                finish(); // 结束当前登录Activity
                            } else {
                                Log.e("LoginActivity", "No Activity found to handle Intent");
                                // 处理下一个Activity未找到的情况
                            }

                            System.out.println(username);
                        } else if ("window".equals(jsonResult.getString("userType"))) {
                            // 用户类型是window
                            Log.d("LoginAsyncTask", "User type: window");
                            intent = new Intent(context, WindowActivity.class);
                            intent.putExtra("window_id", username); // 使用窗口ID或其他标识符

                            if (intent.resolveActivity(getPackageManager()) != null) {
                                startActivity(intent);
                                finish(); // 结束当前登录Activity
                            } else {
                                Log.e("LoginActivity", "No Activity found to handle Intent");
                                // 处理下一个Activity未找到的情况
                            }
                        } else if ("admin".equals(jsonResult.getString("userType"))) {
                            // 用户类型是admin
                            Log.d("LoginAsyncTask", "User type: admin");
                            intent = new Intent(context, AdminActivity.class);
                        } else {
                            // 处理其他用户类型或情景
                            return;
                        }


                        if (intent.resolveActivity(getPackageManager()) != null) {
                            startActivity(intent);
                            finish(); // 结束当前登录Activity
                        } else {
                            Log.e("LoginActivity", "No Activity found to handle Intent");
                            // 处理下一个Activity未找到的情况
                        }
                    }else {
                        // 登录失败
                        String errorMessage = jsonResult.optString("message", "登录失败，请检查用户名和密码");
                        Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    // 在这里处理 JSONException

                    Log.e("LoginAsyncTask", "JSON parsing error", e);
                    Toast.makeText(context, "登录失败，服务器返回异常", Toast.LENGTH_SHORT).show();
                }
            }
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // 在这里为 context 赋值
        context = this;

        Button registerButton = findViewById(R.id.btnReg);



        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击注册按钮时跳转到注册页面
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });

        // Generate and set a random captcha initially
        String captcha = generateRandomCaptcha();
        setRandomCaptchaImage(captcha);

        // Set click listener for refreshing captcha
        ImageView imageViewCaptcha = findViewById(R.id.imageViewCaptcha);
        imageViewCaptcha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newCaptcha = generateRandomCaptcha();
                setRandomCaptchaImage(newCaptcha);
            }
        });
    }

    private String generateRandomCaptcha() {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder captcha = new StringBuilder();
        Random rand = new Random();

        for (int i = 0; i < 1; i++) {
            captcha.append(characters.charAt(rand.nextInt(characters.length())));
        }

        return captcha.toString();
    }

    private void setRandomCaptchaImage(String captcha) {
        generatedCaptcha = captcha;
        Bitmap image = textToImage(captcha, 300, 100);
        ImageView imageViewCaptcha = findViewById(R.id.imageViewCaptcha);
        imageViewCaptcha.setImageBitmap(image);
    }


    private Bitmap textToImage(String text, int width, int height) {
        Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(image);
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setTextSize(40);
        paint.setStyle(Paint.Style.FILL);

        canvas.drawText(text, 10, 50, paint);

        return image;
    }
}
